package org.dataone.dataUsage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.dataone.client.D1RestClient;
import org.dataone.service.util.TypeMarshaller;

public class CNodeMetric {
	private String CN_URL;
	public String getCN_URL() {
		return CN_URL;
	}
	public void setCN_URL(String cN_URL) {
		CN_URL = cN_URL;
	}
	/**
	 * Returns an ArrayList of MonthlyMetric type. The ArrayList contains every
	 * month's download metric of the Coordinating Node.
	 * 
	 * @param timespan
	 *            the time duration of download metric display
	 * @return an ArrayList of metric data
	 */
	public ArrayList<MonthlyMetric> getCNDownloadMetricByMonth(int timespan) {
		ArrayList<MonthlyMetric> result = new ArrayList<MonthlyMetric>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar c1 = Calendar.getInstance();
		c1.add(c1.MONTH, -(timespan + 1));
		for (int i = 0; i < timespan; i++) {
			String metricDate = sdf.format(c1.getTime());
			String starttime = sdf.format(c1.getTime()) + "-01T00:00:00.0000Z";
			c1.add(Calendar.MONTH, 1);
			String endtime = sdf.format(c1.getTime()) + "-01T00:00:00.0000Z";
			try {
				MonthlyMetric temp = new MonthlyMetric();
				temp.setMetricValue(getCNLog(starttime, endtime));
				temp.setMetricDate(metricDate);
				result.add(temp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * This method is to get the download number of an exact startDate and
	 * endDate.
	 * 
	 * @param startDate
	 *            the log data starts point
	 * @param endDate
	 *            the log data ends point
	 * @return exact download number
	 */
	public String getCNLog(String startDate, String endDate) {
		D1RestClient CNclient = new D1RestClient();
		String url = CN_URL + "/cn/v1/log/?event=read&fromDate=" + startDate
				+ "&toDate=" + endDate + "&count=0";
		String result = "";
		try {
			org.dataone.service.types.v1.Log log = TypeMarshaller
					.unmarshalTypeFromStream(
							org.dataone.service.types.v1.Log.class,
							CNclient.doGetRequest(url, true));
			result = Integer.toString(log.getTotal());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
